package cn.hinglo.gameclaw.admin.service;

import cn.hinglo.gameclaw.admin.dao.MorderDao;
import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.data.utils.FieldUtils;
import cn.hinglo.gameclaw.data.utils.IdUtils;
import cn.hinglo.gameclaw.data.utils.ResultUtils;
import cn.hinglo.gameclaw.user.bean.Money;
import cn.hinglo.gameclaw.user.bean.Morder;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @createTime: 2018/5/22
 * @author: HingLo
 * @description: 充值订单的处理
 */
@Service
public class MorderService {

    @Autowired
    private MorderDao morderDao;

    /**
     * 通过传递一个money对象，来添加一个订单信息
     *
     * @param money   充值版对象
     * @param payment 支付方式
     * @return
     */
    public Morder addService(Money money, String userId, int payment) {
        //订单编号的唯一性
        String orderId = IdUtils.getOrderId();
        //将订单信息保存到数据库中
        Morder morder = new Morder().setId(orderId).setUserId(userId).setNum(money.getNum()).setStatus(false).setDate(new Date()).setMid(money.getId());
        morder.setPayment(payment);
        String body = money.getDepict();
        morder.setBody(body);
        String subject = "一块抓娃娃钻石充值";
        morder.setSubject(subject).setBody(body);

        morder.setGold(money.getGold());
        morder.setGiveGold(money.getGiveGold());
        if (morderDao.insert(morder) == 1) {
            return morder;
        } else {
            return null;
        }
    }

    /**
     * 支付成功后，就处理信息
     *
     * @return 返回是否处理成功
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateMorderService(String orderId, Date payDate, String payAccount) {

        //通过订单的Id来查询订单信息
        Morder morder = morderDao.selectByPrimaryKey(orderId);
        //获取订单的状态，如果订单首次通知就修改
        if (!morder.getStatus()) {
            // 获取付款时间
            morder.setPayDate(payDate);
            //支付的支付宝账号
            morder.setPayAccount(payAccount);
            // 设置付款成功
            morder.setStatus(true);
            if (morderDao.updateByPrimaryKey(morder) == 1) {
                //修改用户的砖石数量
                int res = morderDao.updateGoldByUserIdDao(morder.getGold(), morder.getGiveGold(), morder.getUserId());
                if (res == 1) {
                    return true;
                } else {
                    throw new RuntimeException("支付成功,后台处理失败");
                }
            }
        } else {
            //订单已经付款了
            return true;
        }
        return false;
    }

    /**
     * 充值记录详情
     *
     * @param type 支付类型
     * @param date 指定的时间
     * @return 返回结果
     */
    public Result listService(Integer type, Date date) {
        if (type == null) {
            type = FieldUtils.PAYMENT_1;
        }
        if (date == null) {
            date = DateUtil.offsetDay(new Date(), -1);
        }
        return ResultUtils.success(morderDao.listDao(type, date));
    }

    /**
     * 收益统计
     *
     * @param start 开始时间
     * @param end   结束时间段
     * @return 返回结果
     */
    public Result dataListService(Date start, Date end) {
        if (start == null || end == null) {
            Date date = new Date();
            start = DateUtil.offsetDay(date, -6);
            end = date;
        }
        if (end.getTime() > System.currentTimeMillis()) {
            return ResultUtils.error("结束时间不正确");
        }

        Map<String, List<Map<String, Object>>> res = new HashMap<>(2);
        res.put("alipay", de(morderDao.dataListDao(FieldUtils.PAYMENT_1, start, end), start, end));
        res.put("weixin", de(morderDao.dataListDao(FieldUtils.PAYMENT_2, start, end), start, end));

        return ResultUtils.success(res);
    }


    private List<Map<String, Object>> de(List<Map<String, Object>> list, Date start, Date end) {
        // 保证是两个闭区间
        long day = DateUtil.betweenDay(start, end, true) + 1;
        List<Map<String, Object>> res = new ArrayList<>();

        // 如果是空的时候，全部填充数据
        if (list.isEmpty()) {
            for (int i = 0; i < day; i++) {
                Map<String, Object> map1 = new HashMap<>(2);
                map1.put("mon", 0);
                map1.put("date", DateUtil.format(DateUtil.offsetDay(start, i), "yyyy-MM-dd"));
                res.add(map1);
            }
        } else {
            int key = 0;
            for (int i = 0; i < day; i++) {
                String date = "";
                if (key < list.size()) {
                    Map<String, Object> map = list.get(key);
                    date = (String) map.get("date");
                }
                String sf = DateUtil.format(DateUtil.offsetDay(start, i), "yyyy-MM-dd");
                if (!sf.equalsIgnoreCase(date)) {
                    Map<String, Object> map1 = new HashMap<>(2);
                    map1.put("mon", 0);
                    map1.put("date", sf);
                    res.add(map1);
                } else {
                    res.add(list.get(key));
                    key++;
                }

            }
        }
        return res;
    }
}
